//
//  LZYNetworkHelper.m
//  LZYNetworkHelper
//
//  Created by 小宇 on 2016/12/14.
//  Copyright © 2016年 小宇. All rights reserved.
//


#import "LZYNetworkHelper.h"
#import "LZYNetworkCache.h"
#import "SVProgressHUD.h"
#import "AFNetworking.h"
#import "LoginViewController.h"


#ifdef DEBUG
#define LZYLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define LZYLog(...)
#endif
@interface LZYNetworkHelper()<UIWebViewDelegate>
@property (nonatomic,strong) UIView *errorView;
@end

@implementation LZYNetworkHelper
static AFHTTPSessionManager *_manager = nil;
static NetworkStatus _status;
static UIView *_errorView = nil;

#pragma mark - 开始监听网络
+ (void)startMonitoringNetwork
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status)
        {
            case AFNetworkReachabilityStatusUnknown:
                _status(LZYNetworkStatusUnknown);
                break;
            case AFNetworkReachabilityStatusNotReachable:
                _status(LZYNetworkStatusNotReachable);
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                _status(LZYNetworkStatusReachableViaWWAN);
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                _status(LZYNetworkStatusReachableViaWiFi);
                break;
        }
    }];
    [manager startMonitoring];
}

+ (void)networkStatusWithBlock:(NetworkStatus)status
{
    _status = status;
}

#pragma mark - GET请求无缓存
+ (LZYURLSessionTask *)GET:(NSString *)URL parameters:(NSDictionary *)parameters success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure showHub:(BOOL)showHub;
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager *manager = [self createAFHTTPSessionManager:showHub];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:parameters];
    [dic setObject:[[User shareInstance]getUserAccessToken] forKey:@"accessToken"];
    return [manager GET:URL parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [SVProgressHUD dismiss];
        if ([responseObject[@"code"] integerValue] == -1) {
            [[User shareInstance] loginOut];
            LoginViewController *login = [[LoginViewController alloc]init];
            kKeyWindow.rootViewController = login;
        }else if ([responseObject[@"code"] integerValue] == 0){
            [SVProgressHUD showErrorWithStatus:responseObject[@"msg"]];
        }else if ([responseObject[@"code"] integerValue] == 1){
            success(responseObject[@"obj"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        failure ? failure(error) : nil;
        [SVProgressHUD showErrorWithStatus:@"网络访问出错"];
    }];
}

#pragma mark - GET请求自动缓存
+ (LZYURLSessionTask *)GET:(NSString *)URL parameters:(NSDictionary *)parameters responseCache:(HttpRequestCache)responseCache success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure showHub:(BOOL)showHub
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    //读取缓存
    NSString  *CacheUrl = [NSString stringWithFormat:@"%@-%@",URL,[self dictionaryToJson:parameters]];
    
    AFHTTPSessionManager *manager = [self createAFHTTPSessionManager:showHub];
    return [manager GET:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [SVProgressHUD dismiss];
        success(responseObject);
        //对数据进行异步缓存
        [LZYNetworkCache saveResponseCache:responseObject forKey:CacheUrl];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        responseCache([LZYNetworkCache getResponseCacheForKey:CacheUrl]);
        [SVProgressHUD dismiss];
        failure ? failure(error) : nil;
    }];
}

#pragma mark - POST请求无缓存
+ (LZYURLSessionTask *)POST:(NSString *)URL parameters:(NSDictionary *)parameters success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure showHub:(BOOL)showHub
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:parameters];
    if (![NSString isEmpty:[[User shareInstance]getUserAccessToken]]) {
        [dic setObject:[[User shareInstance]getUserAccessToken] forKey:@"accessToken"];
    }
    AFHTTPSessionManager *manager = [self createAFHTTPSessionManager:showHub];
    return [manager POST:URL parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [SVProgressHUD dismiss];
        if ([responseObject[@"code"] integerValue] == -1) {
            LoginViewController *login = [[LoginViewController alloc]init];
            kKeyWindow.rootViewController = login;
        }else if ([responseObject[@"code"] integerValue] == 0){
          [LZYShowMsg showText:responseObject[@"msg"]];
        }else if ([responseObject[@"code"] integerValue] == 1){
            if ([[responseObject allKeys]containsObject:@"obj"]) {
                success(responseObject[@"obj"]);
            }else{
                 success(responseObject);
            }
           
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        failure ? failure(error) : nil;
        [SVProgressHUD showErrorWithStatus:@"网络访问出错"];
    }];
    
}

#pragma mark - POST请求自动缓存
+ (LZYURLSessionTask *)POST:(NSString *)URL parameters:(NSDictionary *)parameters responseCache:(HttpRequestCache)responseCache success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure showHub:(BOOL)showHub
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    //读取缓存
    responseCache([LZYNetworkCache getResponseCacheForKey:URL]);
    
    AFHTTPSessionManager *manager = [self createAFHTTPSessionManager:showHub];
    return [manager POST:URL parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        success(responseObject);
        //对数据进行异步缓存
        [LZYNetworkCache saveResponseCache:responseObject forKey:URL];
        LZYLog(@"responseObject = %@",responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        failure ? failure(error) : nil;
        [SVProgressHUD showErrorWithStatus:@"网络访问出错"];
    }];
    
}

#pragma mark - 上传图片文件
+ (LZYURLSessionTask *)uploadWithURL:(NSString *)URL parameters:(NSDictionary *)parameters images:(NSArray<UIImage *> *)images name:(NSString *)name fileName:(NSString *)fileName mimeType:(NSString *)mimeType progress:(HttLZYrogress)progress success:(HttpRequestSuccess)success failure:(HttpRequestFailed)failure showHub:(BOOL)showHub
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    AFHTTPSessionManager *manager = [self createAFHTTPSessionManager:showHub];
    return [manager POST:URL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        //压缩-添加-上传图片
        [images enumerateObjectsUsingBlock:^(UIImage * _Nonnull image, NSUInteger idx, BOOL * _Nonnull stop) {
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            [formData appendPartWithFileData:imageData name:name fileName:[NSString stringWithFormat:@"%@%ld.%@",fileName,idx,mimeType?mimeType:@"jpeg"] mimeType:[NSString stringWithFormat:@"image/%@",mimeType?mimeType:@"jpeg"]];
        }];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        //上传进度
        progress ? progress(uploadProgress) : nil;
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        success(responseObject);
        LZYLog(@"responseObject = %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        failure ? failure(error) : nil;
        LZYLog(@"error = %@",error);
    }];
}

#pragma mark - 下载文件
+ (LZYURLSessionTask *)downloadWithURL:(NSString *)URL fileDir:(NSString *)fileDir progress:(HttLZYrogress)progress success:(void(^)(NSString *))success failure:(HttpRequestFailed)failure showHub:(BOOL)showHub
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    AFHTTPSessionManager *manager = [self createAFHTTPSessionManager:showHub];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URL]];
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        //下载进度
        progress ? progress(downloadProgress) : nil;
        LZYLog(@"下载进度:%.2f%%",100.0*downloadProgress.completedUnitCount/downloadProgress.totalUnitCount);
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        //拼接缓存目录
        NSString *downloadDir = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:fileDir ? fileDir : @"Download"];
        //打开文件管理器
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //创建Download目录
        [fileManager createDirectoryAtPath:downloadDir withIntermediateDirectories:YES attributes:nil error:nil];
        
        //拼接文件路径
        NSString *filePath = [downloadDir stringByAppendingPathComponent:response.suggestedFilename];
        
        LZYLog(@"downloadDir = %@",downloadDir);
        
        //返回文件位置的URL路径
        return [NSURL fileURLWithPath:filePath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        
        success ? success(filePath.absoluteString /** NSURL->NSString*/) : nil;
        failure && error ? failure(error) : nil;
        
    }];
    
    //开始下载
    [downloadTask resume];
    
    return downloadTask;
    
}


#pragma mark - 设置AFHTTPSessionManager相关属性

+ (AFHTTPSessionManager *)createAFHTTPSessionManager:(BOOL)showHub
{
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager]initWithBaseURL:BASEURL];
    // 对https加密解析
    manager.securityPolicy.allowInvalidCertificates = YES;
    //设置请求参数的类型:HTTP (AFJSONRequestSerializer,AFHTTPRequestSerializer)
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //设置请求的超时时间
    manager.requestSerializer.timeoutInterval = 10.f;
    //设置服务器返回结果的类型:JSON (AFJSONResponseSerializer,AFHTTPResponseSerializer)
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/css",@"text/html",@"text/plain", nil];
    if (showHub) {
        [SVProgressHUD setBackgroundColor:[UIColor clearColor]];
        [SVProgressHUD setOffsetFromCenter:UIOffsetMake(0, 50)];
        [SVProgressHUD show];
    }
    return manager;
}


//词典转换为字符串

+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}


@end
